//
//  SWBasketViewController.swift
//  ChildStory
//  购物车
//  Created by linhan on 2017/1/10.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWBasketViewController: SWBaseViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource,ScrollTabBarDelegate
{
    private var _index:Int = 0
    private var _pageController:UIPageViewController?
    private var _viewControllers:[UIViewController] = []
    private var _tabBar:ScrollTabBar?
    private var _nextBtn:UIButton = UIButton(type: .system)
    private var _statusLabel:UILabel = UILabel()
    private var _countLabel:UILabel = UILabel()
    
    private var _eventCountLabel:UILabel = UILabel()
    private var _subjectCountLabel:UILabel = UILabel()
    private var _customCountLabel:UILabel = UILabel()
    
    
    
    deinit
    {
        SWNotificationCenter.removeObserver(self)
        SWTransactionManager.sharedManager().clearBasket()
        trace("DEINIT SWBasketViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        title = "选择故事"
        view.backgroundColor = UIColor.white
        automaticallyAdjustsScrollViewInsets = false
        
        SWTransactionManager.sharedManager().clearBasket()
        
        let lastY:CGFloat = createTabBar(y: navigationBarBottom, container: view)
        let bottomBarHeight:CGFloat = createBottomBar()
        let pageViewHeight:CGFloat = view.height - bottomBarHeight - lastY
        createPageView(y: lastY, height: pageViewHeight)
        
        createNavigationRightButton("结算", target: self, action: #selector(checkoutBtnTapped))
        
        SWNotificationCenter.addObserver(self, selector: #selector(pageProductCountChangedNotification), name: NotificationName.PageProductCountChanged, object: nil)
        
        pageProductCountChanged()
    }
    
    //
    private func createTabBar(y:CGFloat, container:UIView) -> CGFloat
    {
        let tabBar:ScrollTabBar = ScrollTabBar(frame: CGRectMake(0, y, view.width, 40))
        tabBar.font = UIFont.systemFont(ofSize: 14)
        tabBar.itemSpacing = 30
        tabBar.itemTitleLeftMargin = 10
        tabBar.alignment = .center
        tabBar.selectedColor = UIColor(hex: 0x2f3231)
        tabBar.unselectedColor = UIColor(hex: 0xababab)
        tabBar.delegate = self
        tabBar.titleItems = ["事件故事","趣味故事"]
        tabBar.selectedIndex = _index
        container.addSubview(tabBar)
        _tabBar = tabBar
        
        _eventCountLabel.layer.cornerRadius = 3
        _eventCountLabel.layer.masksToBounds = true
        _eventCountLabel.frame = CGRectMake(0, y, 30, 30)
        _eventCountLabel.backgroundColor = UIColor.darkGray
        container.addSubview(_eventCountLabel)
        
        _subjectCountLabel.layer.cornerRadius = 3
        _subjectCountLabel.layer.masksToBounds = true
        _subjectCountLabel.frame = CGRectMake(100, y, 30, 30)
        _subjectCountLabel.backgroundColor = UIColor.darkGray
        container.addSubview(_subjectCountLabel)
        
        
        return tabBar.bottom
    }
    
    private func createPageView(y:CGFloat, height:CGFloat)
    {
        let rect:CGRect = CGRectMake(0, y, view.width, height)
        
        _viewControllers.append(SWBasketEventPageViewController())
        _viewControllers.append(SWBasketSubjectPageViewController())
        
        
        let pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        pageController.dataSource = self
        pageController.delegate = self
        pageController.setViewControllers([_viewControllers[0]], direction: .forward, animated: true, completion: nil)
        pageController.view?.backgroundColor = UIColor(hex: 0xedeeef)
        pageController.view.frame = rect
        addChildViewController(pageController)
        view.addSubview(pageController.view)
        
        _pageController = pageController
    }
    
    private func createBottomBar() -> CGFloat
    {
        let height:CGFloat = 60
        let bar:UIView = UIView()
        bar.frame = CGRectMake(0, view.height - height, view.width, height)
        view.addSubview(bar)
        
        let statusView:UIView = UIView()
        statusView.frame = CGRectMake(0, 0, view.width, 30)
        bar.addSubview(statusView)
        
        _countLabel.font = UIFont.systemFont(ofSize: 14)
        _countLabel.textColor = UIColor.darkGray
        _countLabel.textAlignment = .right
        _countLabel.frame = CGRectMake(statusView.width - 100, 0, 100, statusView.height)
        statusView.addSubview(_countLabel)
        
        _statusLabel.font = UIFont.systemFont(ofSize: 14)
        _statusLabel.textColor = UIColor.darkGray
        _statusLabel.frame = CGRectMake(0, 0, _countLabel.x, statusView.height)
        statusView.addSubview(_statusLabel)
        
        
        _nextBtn.isEnabled = false
        _nextBtn.backgroundColor = UIColor.lightGray
        _nextBtn.setTitle("2/3 补充图片", for: .normal)
        _nextBtn.addTarget(self, action: #selector(nextBtnTapped), for: .touchUpInside)
        _nextBtn.frame = CGRectMake(0, statusView.bottom, bar.width, 30)
        bar.addSubview(_nextBtn)
        
        return height
    }
    
    private func pageProductCountChanged()
    {
        let pages:[SWPage] = SWTransactionManager.sharedManager().pages.map({$0.page})
        let maxCount:Int = SW.Config.MaxPageCountPerProduct
        let current:Int = pages.count
        var status:String = ""
        if current < maxCount
        {
            status = "还差\(maxCount - current)个故事，就可以做相册啦"
        }
        else if current > maxCount
        {
            status = "多了\(current - maxCount)个故事，只能有\(maxCount)个故事入册哟"
        }
        else
        {
            status = "已完成"
        }
        
        _countLabel.text = "\(current)/\(maxCount)"
        _statusLabel.text = status
        _nextBtn.isEnabled = true
        //_nextBtn.isEnabled = current == maxCount
        
        let eventCount:Int = pages.filter({$0.category == .event}).count
        _eventCountLabel.text = "\(eventCount)"
        
        let subjectCount:Int = pages.filter({$0.category == .subject}).count
        _subjectCountLabel.text = "\(subjectCount)"
        
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of:viewController) , index > 0 else
        {
            return nil
        }
        return _viewControllers.valueAt(index - 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of:viewController) , index < _viewControllers.count - 1 else
        {
            return nil
        }
        return _viewControllers.valueAt(index + 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
    {
        if let currnetViewController = pageViewController.viewControllers?.last , completed
        {
            _index = _viewControllers.index(of:currnetViewController) ?? 0
            _tabBar?.selectedIndex = _index
        }
    }
    
    func scrollTabBar(_ tabBar: ScrollTabBar, didSelectIndex index: Int)
    {
        let direction:UIPageViewControllerNavigationDirection = index > _index ? .forward : .reverse
        if let viewController = _viewControllers.valueAt(index)
        {
            _pageController?.setViewControllers([viewController], direction: direction, animated: true, completion: nil)
        }
    }
    
    @objc private func nextBtnTapped()
    {
        let viewController = SWBasketEditingViewController()
        navigationController?.pushViewController(viewController, animated: true)
    }
    
    @objc private func pageProductCountChangedNotification()
    {
        pageProductCountChanged()
    }
    
    @objc private func checkoutBtnTapped()
    {
        navigationController?.pushViewController(SWCheckoutViewController(), animated: true)
    }
    
    
    
}
